package test.hello.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import com.alibaba.nacos.client.naming.utils.StringUtils;

public class FtpUtil {
    public static FTPClient ftpConnection(String ip,String port, String username, String password) throws IOException {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip, Integer.parseInt(port));
            ftpClient.login(username, password);
            int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
            if(!FTPReply.isPositiveCompletion(replyCode)) {
                ftpClient.disconnect();
                System.exit(1);
            }
            ftpClient.enterLocalPassiveMode();//这句最好加告诉对面服务器开一个端口
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setBufferSize(526);
            System.out.println("连接成功！");
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpClient;
    }
    
    public static void close(FTPClient ftpClient) throws IOException{
        if(ftpClient!=null && ftpClient.isConnected()){
            ftpClient.logout();
            ftpClient.disconnect();
        }
    }
    public static boolean downFile(FTPClient ftpClient, String newFileName, String fileName, String downUrl) throws IOException {
        boolean isTrue = false;
        OutputStream os=null;
        File localFile = new File(downUrl + "/" + newFileName);
        if (!localFile.getParentFile().exists()){//文件夹目录不存在创建目录
            localFile.getParentFile().mkdirs();
            localFile.createNewFile();
        }
        os = new FileOutputStream(localFile);
        isTrue = ftpClient.retrieveFile(new String(fileName.getBytes(),"ISO-8859-1"), os);
        os.close();
        return isTrue;
    }
    
    public static boolean createDir(String dir,FTPClient ftpClient){
		if(StringUtils.isEmpty(dir))
			return true;
		String d;
		try {
		  	ftpClient.changeWorkingDirectory("file/03ReqEnc");
			//目录编码，解决中文路径问题
			d = new String(dir.toString().getBytes("GBK"),"iso-8859-1");
			//尝试切入目录
			if(ftpClient.changeWorkingDirectory(d))
				return true;
			String[] arr =  dir.split("/");
			StringBuffer sbfDir=new StringBuffer();
			//循环生成子目录
			for(String s : arr){
				sbfDir.append(s);
				sbfDir.append("/");
				//目录编码，解决中文路径问题
				d = new String(sbfDir.toString().getBytes("GBK"),"iso-8859-1");
				//尝试切入目录
				if(ftpClient.changeWorkingDirectory(d))
					continue;
				if(!ftpClient.makeDirectory(d)){
					System.out.println("[失败]ftp创建目录："+sbfDir.toString());
					return false;
				}
				System.out.println("[成功]创建ftp目录："+sbfDir.toString());
			}
			//将目录切换至指定路径
			return ftpClient.changeWorkingDirectory(d);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

    
    public static void main(String[] args) throws IOException {
    	FTPClient ftpClient = ftpConnection("47.93.30.147","21","myftp","ftp123");
    	createDir("sh001",ftpClient);
    	
	}
}
